package com.example.familylibrary.service.impl;

import com.example.familylibrary.dto.ReadingProgressDTO;
import com.example.familylibrary.entity.BookEntity;
import com.example.familylibrary.entity.ReadingProgressEntity;
import com.example.familylibrary.repository.BookRepository;
import com.example.familylibrary.repository.ReadingProgressRepository;
import com.example.familylibrary.service.ReadingProgressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReadingProgressServiceImpl implements ReadingProgressService {

    @Autowired
    private ReadingProgressRepository readingProgressRepository;

    @Autowired
    private BookRepository bookRepository;

    @Override
    public ReadingProgressDTO createOrUpdateProgress(ReadingProgressDTO readingProgressDTO) {
        // 查找是否已存在该用户的图书进度记录
        ReadingProgressEntity progressEntity = readingProgressRepository
                .findByUserIdAndBookId(readingProgressDTO.getUserId(), readingProgressDTO.getBookId())
                .orElse(new ReadingProgressEntity());

        // 更新进度信息
        BeanUtils.copyProperties(readingProgressDTO, progressEntity);

        // 如果是新建记录，设置默认值
        if (progressEntity.getId() == null) {
            progressEntity.setUserId(readingProgressDTO.getUserId());
            progressEntity.setBookId(readingProgressDTO.getBookId());
            progressEntity.setCurrentPage(readingProgressDTO.getCurrentPage() != null ? 
                readingProgressDTO.getCurrentPage() : 0);
            progressEntity.setProgressPercent(readingProgressDTO.getProgressPercent() != null ? 
                readingProgressDTO.getProgressPercent() : BigDecimal.ZERO);
            progressEntity.setStatus(readingProgressDTO.getStatus() != null ? 
                readingProgressDTO.getStatus() : 1);
        }

        // 计算进度百分比
        if (progressEntity.getCurrentPage() != null && progressEntity.getCurrentPage() > 0) {
            BookEntity book = bookRepository.findById(progressEntity.getBookId())
                    .orElseThrow(() -> new RuntimeException("图书不存在"));
            if (book.getPages() != null && book.getPages() > 0) {
                BigDecimal percent = new BigDecimal(progressEntity.getCurrentPage())
                        .multiply(BigDecimal.valueOf(100))
                        .divide(new BigDecimal(book.getPages()), 2, BigDecimal.ROUND_HALF_UP);
                progressEntity.setProgressPercent(percent);
            }
        }

        ReadingProgressEntity savedProgress = readingProgressRepository.save(progressEntity);

        ReadingProgressDTO result = new ReadingProgressDTO();
        BeanUtils.copyProperties(savedProgress, result);
        return result;
    }

    @Override
    public ReadingProgressDTO getProgressByUserAndBook(Long userId, Long bookId) {
        ReadingProgressEntity progressEntity = readingProgressRepository
                .findByUserIdAndBookId(userId, bookId)
                .orElseThrow(() -> new RuntimeException("阅读进度记录不存在"));

        ReadingProgressDTO result = new ReadingProgressDTO();
        BeanUtils.copyProperties(progressEntity, result);
        return result;
    }

    @Override
    public List<ReadingProgressDTO> getProgressByUserId(Long userId) {
        return readingProgressRepository.findByUserId(userId).stream().map(progressEntity -> {
            ReadingProgressDTO progressDTO = new ReadingProgressDTO();
            BeanUtils.copyProperties(progressEntity, progressDTO);
            return progressDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ReadingProgressDTO> getProgressByBookId(Long bookId) {
        return readingProgressRepository.findByBookId(bookId).stream().map(progressEntity -> {
            ReadingProgressDTO progressDTO = new ReadingProgressDTO();
            BeanUtils.copyProperties(progressEntity, progressDTO);
            return progressDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public ReadingProgressDTO updateProgressStatus(Long id, Integer status) {
        ReadingProgressEntity progressEntity = readingProgressRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("阅读进度记录不存在"));

        progressEntity.setStatus(status);
        
        // 如果状态为已读，设置完成日期
        if (status == 2) {
            progressEntity.setFinishReadDate(java.time.LocalDate.now());
        }

        ReadingProgressEntity updatedProgress = readingProgressRepository.save(progressEntity);

        ReadingProgressDTO result = new ReadingProgressDTO();
        BeanUtils.copyProperties(updatedProgress, result);
        return result;
    }
}